package org.pms.demo.webservice.controller;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.pms.demo.webservice.exception.IMReadException;
import org.pms.demo.webservice.utils.ProjectUtils;
import org.pms.demo.webservice.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by xusaike on 17/5/31.
 */
@Component
@Path("/v{version}/auth")
public class AuthVersionRestController {


    @POST
    @Path("/login")
    public String login(@HeaderParam("user-agent") String user_agent,@PathParam("version")String version,
                        @Context HttpServletResponse response, @Context HttpServletRequest request,@Context HttpHeaders headers,
                        @FormParam("username") String username, @FormParam("password") String password,
                        @HeaderParam("info-channel")String headerChanel, @HeaderParam("info-appid")String appid){
        try{
            String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");
            String error = null;
            if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
                error = "用户名/密码错误";
            } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                error = "用户名/密码错误";
            } else if(exceptionClassName != null) {
                error = "其他错误：" + exceptionClassName;
            }
            if(request.getParameter("forceLogout") != null) {
               error="您已经被管理员强制退出，请重新登录";
            }
            if(!StringUtils.isNullOrEmpty(error)){
                return ProjectUtils.getErrorMsg(error);
            }else{
                Subject currentUser = SecurityUtils.getSubject();//获取当前用户
                return ProjectUtils.getContentMsg(currentUser.getPrincipal().toString());
            }
        }catch (Exception e){
            IMReadException.printf(e);
        }
        return ProjectUtils.getErrorMsg("error");


        /*Subject currentUser = SecurityUtils.getSubject();//获取当前用户
        if(currentUser!=null)
            currentUser.logout(); //执行登出操作,移除对应的session以及权限数据。



        *//*  String rand = (String)request.getSession().getAttribute("rand");
       String captcha = WebUtils.getCleanParam(request, "captcha");
        System.out.println("用户["+username+"]登录时输入的验证码为["+captcha+"]，HttpSession中的验证码为["+rand+"]");
        if(!StringUtils.equals(rand, captcha)){
            request.setAttribute("message_login", "验证码不正确");
            return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
        }*//*
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //token.setRememberMe(true);
        //获取当前的Subject
        currentUser = SecurityUtils.getSubject();
        try {
            //在调用了login方法后，SecurityManager会收到AuthenticationToken，并将其发送给已配置的Realm执行必须的认证检查
            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            //所以这一步在调用login(token)方法时，它会走到MyRealm.doGetAuthenticationInfo()方法中，具体验证方式详见此方法
            currentUser.login(token);
        }catch(UnknownAccountException uae){
            request.setAttribute("message_login", "用户名或密码错误");
        }catch(IncorrectCredentialsException ice){
            request.setAttribute("message_login", "用户名或密码错误");
        }catch(LockedAccountException lae){
            request.setAttribute("message_login", "账户已锁定");
        }catch(ExcessiveAttemptsException eae){
            request.setAttribute("message_login", "用户名或密码错误次数过多");
        }catch(AuthenticationException ae){
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            ae.printStackTrace();
            request.setAttribute("message_login", "用户名或密码不正确");
        }
        //验证是否登录成功
        if(currentUser.isAuthenticated()){


           *//* java.util.Enumeration   e   =   request.getSession().getAttributeNames();

            while( e.hasMoreElements())   {
                String sessionName=(String)e.nextElement();
                System.out.println("\n*****session item name="+sessionName);
                System.out.println("\n****session item value="+request.getSession().getAttribute(sessionName));
            }*//*

            return ProjectUtils.getContentMsg(username);
        }else{
            token.clear();
            return ProjectUtils.getErrorMsg((String)request.getAttribute("message_login"));
        }*/
    }
    @GET
    @Path("logout")
    public String logout(){
        try{
            Subject currentUser = SecurityUtils.getSubject();//获取当前用户

            currentUser.logout(); //执行登出操作,移除对应的session以及权限数据。
            return ProjectUtils.getContentMsg("操作成功");
        }catch (Exception e){
            IMReadException.printf(e);
        }
        return ProjectUtils.getErrorMsg("error");
    }
    @GET
    @Path("login/success")
    public String success(){
        try{
            Subject currentUser = SecurityUtils.getSubject();//获取当前用户
            return ProjectUtils.getContentMsg(currentUser.getPrincipal().toString());
        }catch (Exception e){
            IMReadException.printf(e);
        }
        return ProjectUtils.getErrorMsg("error");
    }
}
